
package com.wakala.employment.fragment.trending;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wakala.employment.R;
import com.wakala.employment.adapter.base.broccoli.BroccoliRecyclerAdapter;
import com.wakala.employment.adapter.base.broccoli.BroccoliSimpleDelegateAdapter;
import com.wakala.employment.adapter.base.delegate.SimpleDelegateAdapter;
import com.wakala.employment.adapter.jobCategory.JobCategoryTreeVo;
import com.wakala.employment.adapter.search.SearchAdapter;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.constants.Constants;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentTrendingBinding;
import com.wakala.employment.fragment.other.CitySelectFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.ArticleVo;
import com.wakala.employment.http.bean.JobBookingBo;
import com.wakala.employment.http.bean.JobBookingVo;
import com.wakala.employment.http.bean.JobCategoryVo;
import com.wakala.employment.http.bean.ResumeInfoPage;
import com.wakala.employment.http.bean.SystemCityTreeVo;
import com.wakala.employment.utils.DemoDataProvider;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.CollectionUtils;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ThemeUtils;
import com.xuexiang.xui.utils.Utils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xutil.XUtil;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import me.samlss.broccoli.Broccoli;

/**
 * 订阅工作
 *
 * @author xuexiang
 * @since 2019-10-30 00:19
 */
@Page(anim = CoreAnim.none)
public class TrendingFragment extends BaseFragment<FragmentTrendingBinding> implements View.OnClickListener {

    private static final String TAG = "TrendingFragment";

    private List<String> mList = Lists.newArrayList();

    private Map<String,JobCategoryVo> jobCategoryVoMap = Maps.newHashMap();

    private SearchAdapter<String> jobNameAdapter;

    private ArrayList<SystemCityTreeVo> selectedCityList = new ArrayList<>();

    private RecyclerView mRecyclerView;

    private List<JobCategoryVo> jobCategoryList = Lists.newArrayList();

    private SimpleDelegateAdapter<JobCategoryVo> mNewsAdapter;

    @NonNull
    @Override
    protected FragmentTrendingBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentTrendingBinding.inflate(inflater, container, attachToRoot);
    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        requireActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.xui_config_color_light));
        return null;
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==Constants.REQ_RESULT_101){
            //--城市选择返回结果
            selectedCityList = data.getParcelableArrayListExtra("selectedCityList");
           //将selectedJobList列表元素的name生成逗号分割的字符串
            List<String> jobNameList = Lists.newArrayList();
            if(!CollectionUtils.isEmpty(selectedCityList)){
                selectedCityList.forEach(jobCategoryTreeVo -> jobNameList.add(jobCategoryTreeVo.getName()));
            }
            String jobNameText = String.join(",",jobNameList);
            binding.tvSelectedCityName.setText(jobNameText);
            //将selectedJobList中的对象的id转为逗号分割的数组
            String jobVCityId = selectedCityList.stream().map(SystemCityTreeVo::getCityId).map(String::valueOf).collect(Collectors.joining(","));

            JobBookingBo jobBookingBo = new JobBookingBo();
            jobBookingBo.setJobCityId(jobVCityId);
            addJobBooking(jobBookingBo);
        }
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initViews() {
        mRecyclerView = binding.rvJobList;
        WidgetUtils.initRecyclerView(mRecyclerView, DensityUtils.dp2px(getContext(), 1), ThemeUtils.resolveColor(getContext(), R.attr.colorPrimaryWhile));
        mNewsAdapter = new BroccoliSimpleDelegateAdapter<JobCategoryVo>(R.layout.item_job_booking_job_category,new LinearLayoutHelper(), DemoDataProvider.getEmptyJobCategory()) {

            @Override
            protected void onBindData(RecyclerViewHolder holder, JobCategoryVo model, int position) {
                holder.text(R.id.tvJobName, model.getName());
                holder.click(R.id.ivArrow, v -> {
                    // 跳转到选择工种页面
                });
                holder.click(R.id.ivDelete, v -> {
                    jobCategoryList.removeIf(item -> Objects.equals(item.getId(), model.getId()));
                    mNewsAdapter.refresh(jobCategoryList);
                    binding.tvJobCategoryCount.setText(jobCategoryList.size()+"");
                    JobBookingBo jobBookingBo = new JobBookingBo();
                    String jobCategoryId = jobCategoryList.stream().map(JobCategoryVo::getId).map(String::valueOf).collect(Collectors.joining(","));
                    jobBookingBo.setJobCategoryId(jobCategoryId);

                    //提交
                    addJobBooking(jobBookingBo);
                });
            }

            @Override
            protected void onBindBroccoli(RecyclerViewHolder holder, Broccoli broccoli) {
                broccoli.addPlaceholders(
                        holder.findView(R.id.iv_avatar),
                        holder.findView(R.id.tvJobName),
                        holder.findView(R.id.ivArrow),
                        holder.findView(R.id.ivDelete)
                );
            }
        };
        mRecyclerView.setAdapter(mNewsAdapter);
        //加载工种信息
        getJobCategoryList();
        getJobBookingInfo();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initListeners() {
        super.initListeners();
        binding.rlNotifyCity.setOnClickListener(this);
        jobNameAdapter = new SearchAdapter<>(requireContext(), R.layout.custom_autocomplete_item, mList,SearchAdapter.ALL);
        binding.etSearchJobName.setAdapter(jobNameAdapter);
        //设置输入一个字就自动提示，默认是两个
        binding.etSearchJobName.setThreshold(1);
        binding.etSearchJobName.setOnClickListener(v -> {
            binding.etSearchJobName.showDropDown();
        });
        binding.btnSearch.setOnClickListener(v -> {
            String jobName = binding.etSearchJobName.getText().toString();
            if(StringUtils.isEmpty(jobName)){
                XToastUtils.info("请输入工种名称");
                return;
            }
            JobCategoryVo jobCategoryVo = jobCategoryVoMap.get(jobName);
            if(null==jobCategoryVo){
                XToastUtils.info("未找到该工种");
            }else{
                //跳转到搜索页面
                XToastUtils.info("请选择列表中的工种进行添加");
                //XRouter.getInstance().build(RouterActivityPath.Search.PAGE_SEARCH).withString("jobName",jobName).navigation();
            }
            //跳转到搜索页面
            //XRouter.getInstance().build(RouterActivityPath.Search.PAGE_SEARCH).navigation();
            //跳转到搜索页面
            //XRouter.getInstance().build(RouterActivityPath.Search.PAGE_SEARCH).withString("jobName",jobName).navigation();
        });
        binding.etSearchJobName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (s.length() > 0) {
                    binding.etSearchJobName.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_close_circle_gray, 0);
                } else {
                    binding.etSearchJobName.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
                }

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.i(TAG, "-------------工种关键字------------------"+s);
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.i(TAG, "-------------工种关键字------------------");
            }
        });
        binding.etSearchJobName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(jobCategoryList.size()>5){
                    ToastUtils.toast("最多选择5种工种");
                    return;
                }
                String selectedItem = (String) parent.getItemAtPosition(position);
                JobCategoryVo jobCategoryVo = jobCategoryVoMap.get(selectedItem);
                List<String> jobCategoryIdList= jobCategoryList.stream().map(JobCategoryVo::getId).map(String::valueOf).collect(Collectors.toList());
                if(jobCategoryVo != null){
                    if(!jobCategoryIdList.contains(String.valueOf(jobCategoryVo.getId()))){
                        jobCategoryList.add(jobCategoryVo);
                        mNewsAdapter.refresh(jobCategoryList);
                        binding.tvJobCategoryCount.setText(jobCategoryList.size()+"");
                        binding.etSearchJobName.setText(jobCategoryVo.getName());
                        JobBookingBo jobBookingBo = new JobBookingBo();
                        String jobCategoryId = jobCategoryList.stream().map(JobCategoryVo::getId).map(String::valueOf).collect(Collectors.joining(","));
                        jobBookingBo.setJobCategoryId(jobCategoryId);

                        //提交
                        addJobBooking(jobBookingBo);
                    }else {
                        ToastUtils.toast("您已经订阅该职位");
                    }

                }
                // 处理选中项
                Log.d("Selected Item", selectedItem);
            }
        });
        //
        binding.etSearchJobName.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                // 判断触碰是否结束
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    // 判断所触碰的位置是否为清除的按钮
                    if (motionEvent.getX() > (binding.etSearchJobName.getWidth() - binding.etSearchJobName.getTotalPaddingRight())
                            && motionEvent.getX() < (binding.etSearchJobName.getWidth() - binding.etSearchJobName.getPaddingRight())) {
                        // 将editText里面的内容清除
                        binding.etSearchJobName.setText("");
                        binding.etSearchJobName.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
                    }
                }
                return false;
            }
        });
    }

    @Override
    protected void startLazyData() {
        super.startLazyData();
        this.initTitle();
        //getJobCategoryList();
        getJobBookingInfo();

    }

    @SuppressLint("CheckResult")
    private void addJobBooking(JobBookingBo bo) {
        appLoadingDialog.show();
        XHttpProxy.proxy(TestApi.IOther.class)
                .addJobBooking(bo)
                .subscribeWith(new NoTipRequestSubscriber<Object>() {

                    @Override
                    protected void onSuccess(Object result) {
                        Log.e(TAG, "-------------添加/更新订阅------------------");
                        appLoadingDialog.dismiss();
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        appLoadingDialog.dismiss();
                        Log.e(TAG, "-------------添加/更新订阅--错误------------------");
                        Log.e(TAG, Objects.requireNonNull(e.getMessage()));
                    }

                });
    }

    @SuppressLint("CheckResult")
    private void getJobBookingInfo() {
        appLoadingDialog.show();
        XHttpProxy.proxy(TestApi.IOther.class)
                .getJobBookingInfo()
                .subscribeWith(new NoTipRequestSubscriber<JobBookingVo>() {
                    @SuppressLint({"CheckResult", "NotifyDataSetChanged"})
                    @Override
                    protected void onSuccess(JobBookingVo jobBookingVo) {
                       if(null!=jobBookingVo){
                           Log.e(TAG, "-------------订阅信息------------------");
                           if(StringUtils.isEmpty(jobBookingVo.getJobCityName())){
                               binding.tvSelectedCityName.setText("请选择订阅城市");
                           }else {
                               binding.tvSelectedCityName.setText(jobBookingVo.getJobCityName());
                           }
                           if(!CollectionUtils.isEmpty(jobBookingVo.getJobCategoryVoList())){
                               jobCategoryList.clear();
                               jobCategoryList.addAll(jobBookingVo.getJobCategoryVoList());
                               mNewsAdapter.refresh(jobCategoryList);
                               //
                               binding.tvJobCategoryCount.setText(jobCategoryList.size()+"");
                           }else {
                               mNewsAdapter.refresh(jobCategoryList);
                           }
                           appLoadingDialog.dismiss();
                       }

                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        appLoadingDialog.dismiss();
                        Log.e(TAG, "-------------订阅列表--错误------------------");
                        Log.e(TAG, Objects.requireNonNull(e.getMessage()));
                    }

                });
    }

    @SuppressLint("CheckResult")
    private void getJobCategoryList() {
        appLoadingDialog.show();
        XHttpProxy.proxy(TestApi.IOther.class)
                .getJobCategoryLeafList()
                .subscribeWith(new NoTipRequestSubscriber<List<JobCategoryVo>>() {
                    @Override
                    protected void onSuccess(List<JobCategoryVo> jobCategoryVoList) {
                        if(!CollectionUtils.isEmpty(jobCategoryVoList)){
                            Log.i(TAG, "-------------工种信息列表------------------");
                            Log.i(TAG, GsonUtils.toJson(jobCategoryVoList));
                            mList.clear();
                            mList =jobCategoryVoList.stream().map(JobCategoryVo::getName).collect(Collectors.toList());
                            jobCategoryVoMap=jobCategoryVoList.stream().collect(Collectors.toMap(JobCategoryVo::getName, jobCategoryVo -> jobCategoryVo));
                            jobNameAdapter = new SearchAdapter<>(requireContext(), R.layout.custom_autocomplete_item, mList,SearchAdapter.ALL);
                            binding.etSearchJobName.setAdapter(jobNameAdapter);
                            jobNameAdapter.notifyDataSetChanged();
                            Log.i(TAG, GsonUtils.toJson(mList));
                        }else {
                            jobNameAdapter.notifyDataSetInvalidated();
                        }
                        appLoadingDialog.dismiss();

                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        appLoadingDialog.dismiss();
                        Log.e(TAG, "-------------工种信息列表--错误------------------");
                        Log.e(TAG, Objects.requireNonNull(e.getMessage()));
                    }

                });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id == R.id.rl_notify_city){
            openNewPageForResult(CitySelectFragment.class.getSimpleName(), Constants.REQ_RESULT_101);
        }
    }
}
